/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session04;

import com.sun.org.apache.xml.internal.security.utils.Base64;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;

/**
 *
 * @author sinhnx <sinhnx@fpt.aptech.ac.vn>
 */
public class RSA {

    public static void main(String[] args) {
        try {
            String msg = "Tôi là người Việt Nam";

            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(512);
            KeyPair kp = kpg.genKeyPair();
            PublicKey publicKey = kp.getPublic();
            PrivateKey privateKey = kp.getPrivate();

            //Encrypt
            Cipher ci = Cipher.getInstance("RSA");
            ci.init(Cipher.ENCRYPT_MODE, publicKey);

            //Xau da duoc ma hoa
            String encrypt = Base64.encode(ci.doFinal(msg.getBytes()));
            System.out.println("ENCRYPT: " + encrypt);

            //Giai ma
            ci.init(Cipher.DECRYPT_MODE, privateKey);
            //Xau da duoc giai ma
            String decrypt = new String(ci.doFinal(Base64.decode(encrypt)));
            System.out.println("DECRYPT: " + decrypt);
        } catch (Exception ex) {
            Logger.getLogger(RSA.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}